'use client'

import { useEffect, useState } from 'react'
import { useParams, useRouter } from 'next/navigation'
import { DragDropContext, Droppable, Draggable } from '@hello-pangea/dnd'
import { ArrowLeftIcon, PlusIcon, Bars3Icon, XMarkIcon, TrashIcon } from '@heroicons/react/24/outline'
import NewProjectModal from '@/components/NewProjectModal'
import NewTodoModal from '@/components/NewTodoModal'
import ProjectSidebar from '@/components/ProjectSidebar'

interface Todo {
  id: number
  content: string
  created_by: number
  creator_name: string
  creator_color: string
  tags: string | null
  status: '待完成' | '进行中' | '待测试' | '已完成'
  assigned_to: number | null
  assignee_name: string | null
  assignee_color: string | null
  created_at: string
  completion_time?: string | null
  time_spent?: number | null
}

interface User {
  id: number
  name: string
  email: string
  color: string
  avatar?: string
}

interface Project {
  id: number
  name: string
  description: string
  isArchived: boolean
  created_at: string
}

const statusColumns = [
  { id: '待完成', title: '待完成', color: 'bg-neutral-200', emoji: '📝' },
  { id: '进行中', title: '进行中', color: 'bg-blue-100', emoji: '💪' },
  { id: '待测试', title: '待测试', color: 'bg-yellow-100', emoji: '🧪' },
  { id: '已完成', title: '已完成', color: 'bg-green-100', emoji: '✅' },
]

export default function TodoListPage() {
  const params = useParams()
  const router = useRouter()
  const projectName = decodeURIComponent(params.projectName as string)
  
  const [project, setProject] = useState<Project | null>(null)
  const [projectMembers, setProjectMembers] = useState<User[]>([])
  const [currentUser, setCurrentUser] = useState<User | null>(null)
  const [todos, setTodos] = useState<Record<string, Todo[]>>({
    '待完成': [],
    '进行中': [],
    '待测试': [],
    '已完成': [],
  })
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const [isSidebarOpen, setIsSidebarOpen] = useState(true)
  const [isNewProjectModalOpen, setIsNewProjectModalOpen] = useState(false)
  const [isEditProjectModalOpen, setIsEditProjectModalOpen] = useState(false)
  const [isNewTodoModalOpen, setIsNewTodoModalOpen] = useState(false)
  const [currentTodoStatus, setCurrentTodoStatus] = useState<string | null>(null)
  const [editingTodo, setEditingTodo] = useState<Todo | null>(null)
  const [isCompactMode, setIsCompactMode] = useState(false)

  useEffect(() => {
    fetchProjectAndTodos()
    fetchCurrentUser()
  }, [projectName])

  const fetchCurrentUser = async () => {
    try {
      const response = await fetch('/api/user/me')
      if (response.ok) {
        const user = await response.json()
        setCurrentUser(user)
      } else {
        const errorData = await response.json()
        if (errorData.casdoorError) {
          // Casdoor相关错误，显示用户友好的错误信息
          alert(`认证服务暂时不可用：${errorData.error}\n\n请检查网络连接或联系管理员。`)
          // 重定向到登录页面
          router.push('/auth/login')
        } else {
          // 其他错误
          console.error('获取当前用户失败:', errorData.error)
        }
      }
    } catch (err) {
      console.error('获取当前用户失败:', err)
      // 网络错误或其他异常
      alert('无法连接到服务器，请检查网络连接后重试。')
    }
  }

  const fetchProjectAndTodos = async () => {
    setLoading(true)
    setError('')
    try {
      // 1. 根据projectName获取项目完整信息 (包括ID)
      const projectByNameResponse = await fetch(`/api/projects/by-name/${encodeURIComponent(projectName)}`)
      if (!projectByNameResponse.ok) {
        if (projectByNameResponse.status === 404) {
          setError('项目不存在')
        } else if (projectByNameResponse.status === 403) {
          setError('您没有访问此项目的权限')
        } else {
          setError('加载项目失败')
        }
        setLoading(false)
        return
      }
      const projectData = await projectByNameResponse.json()
      setProject(projectData)
      const projectId = projectData.id // 获取项目ID

      // 2. 使用projectId获取项目成员
      const membersResponse = await fetch(`/api/projects/${projectId}/members`)
      if (membersResponse.ok) {
        const membersData = await membersResponse.json()
        setProjectMembers(membersData)
      }

      // 3. 使用projectId获取项目的todos
      const todosResponse = await fetch(`/api/projects/${projectId}/todos`)
      if (todosResponse.ok) {
        const todosData = await todosResponse.json()

        const groupedTodos: Record<string, Todo[]> = {
          '待完成': [], '进行中': [], '待测试': [], '已完成': [],
        }
        todosData.forEach((apiItem: any) => { 
          const todo: Todo = {
            id: apiItem.todolist_id, 
            content: apiItem.content,
            created_by: apiItem.created_by,
            creator_name: apiItem.creator_name || '未知创建者',
            creator_color: apiItem.creator_color || '#888888',
            tags: apiItem.tags || null,
            status: apiItem.status, 
            assigned_to: apiItem.assigned_to || null,
            assignee_name: apiItem.assignee_name || null,
            assignee_color: apiItem.assignee_color || null,
            created_at: apiItem.created_at, 
            completion_time: apiItem.completion_time || null,
            time_spent: apiItem.time_spent || null,
          };

          if (todo.status && groupedTodos[todo.status]) {
             groupedTodos[todo.status].push(todo);
          } else {
            console.warn(`Todo with id ${todo.id} (original todolist_id: ${apiItem.todolist_id}) has an invalid or missing status: '${apiItem.status}'. Placing in '待完成'.`);
            groupedTodos['待完成'].push({...todo, status: '待完成'});
          }
        });
        setTodos(groupedTodos)
      }
    } catch (err) {
      setError('网络错误')
    } finally {
      setLoading(false)
    }
  }

  const removeMember = async (memberId: number) => {
    if (!project) return;
    if (currentUser && memberId === currentUser.id) {
      alert('不能移除项目创建者')
      return
    }
    if (confirm('确定要移除该成员吗？')) {
      try {
        const response = await fetch(`/api/projects/${project.id}/members/${memberId}`, {
          method: 'DELETE',
        })
        if (response.ok) {
          setProjectMembers(projectMembers.filter(m => m.id !== memberId))
        } else {
          alert('移除成员失败')
        }
      } catch (err) {
        console.error('移除成员失败:', err)
        alert('移除成员失败')
      }
    }
  }

  const handleDragEnd = async (result: any) => {
    if (!result.destination) return

    const { source, destination, draggableId } = result
    
    if (source.droppableId === destination.droppableId) {
      // 同一列内重新排序
      const column = source.droppableId
      const columnTodos = [...todos[column]]
      const [removed] = columnTodos.splice(source.index, 1)
      columnTodos.splice(destination.index, 0, removed)
      
      setTodos({
        ...todos,
        [column]: columnTodos
      })
    } else {
      // 跨列移动
      const sourceColumn = source.droppableId
      const destColumn = destination.droppableId
      const sourceTodos = [...todos[sourceColumn]]
      const destTodos = [...todos[destColumn]]
      const [moved] = sourceTodos.splice(source.index, 1)
      destTodos.splice(destination.index, 0, moved)
      
      setTodos({
        ...todos,
        [sourceColumn]: sourceTodos,
        [destColumn]: destTodos
      })

      // 更新数据库中的状态
      try {
        const response = await fetch(`/api/todos/${moved.id}`, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ status: destColumn }),
        })
        if (!response.ok) {
          console.error('更新todo状态失败')
        }
      } catch (err) {
        console.error('更新todo状态失败:', err)
      }
    }
  }

  const handleDeleteTodo = async (todoId: number, status: Todo['status']) => {
    if (confirm('确定要删除这个任务吗？')) {
      try {
        const response = await fetch(`/api/todos/${todoId}`, {
          method: 'DELETE',
        })
        if (response.ok) {
          setTodos(prevTodos => ({
            ...prevTodos,
            [status]: prevTodos[status].filter(todo => todo.id !== todoId)
          }))
        } else {
          alert('删除任务失败')
        }
      } catch (err) {
        console.error('删除任务失败:', err)
        alert('删除任务失败')
      }
    }
  }

  const openNewTodoModal = (status: string) => {
    setEditingTodo(null)
    setCurrentTodoStatus(status)
    setIsNewTodoModalOpen(true)
  }

  const openEditTodoModal = (todo: Todo) => {
    setEditingTodo(todo)
    setCurrentTodoStatus(todo.status)
    setIsNewTodoModalOpen(true)
  }

  const handleTodoSubmitSuccess = (submittedTodo: Todo) => {
    setTodos(prevTodos => {
      const statusTodos = prevTodos[submittedTodo.status] || [];
      const existingIndex = statusTodos.findIndex(t => t.id === submittedTodo.id);
      
      if (existingIndex !== -1) {
        // 更新现有todo
        const updatedStatusTodos = statusTodos.map(t => 
          t.id === submittedTodo.id ? submittedTodo : t
        );
        return {
          ...prevTodos,
          [submittedTodo.status]: updatedStatusTodos,
        };
      } else {
        return {
          ...prevTodos,
          [submittedTodo.status]: [submittedTodo, ...statusTodos],
        };
      }
    });
    setIsNewTodoModalOpen(false);
    setEditingTodo(null);
  };

  // 过滤已完成超过一周的todo
  const getFilteredTodos = (status: string, todosList: Todo[]) => {
    if (status === '已完成' && isCompactMode) {
      const oneWeekAgo = new Date();
      oneWeekAgo.setDate(oneWeekAgo.getDate() - 7);
      
      return todosList.filter(todo => {
        // 使用完成时间（completion_time）而不是创建时间（created_at）
        const completionDate = todo.completion_time ? new Date(todo.completion_time) : new Date(todo.created_at);
        return completionDate > oneWeekAgo;
      });
    }
    return todosList;
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-100 flex items-center justify-center">
        <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-indigo-600"></div>
      </div>
    )
  }

  if (error) {
    return (
      <div className="min-h-screen bg-gray-100 flex items-center justify-center">
        <div className="text-center">
          <p className="text-red-600 mb-4">{error}</p>
          <button
            onClick={() => router.push('/dashboard')}
            className="bg-gray-600 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded"
          >
            返回仪表板
          </button>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gray-100 flex">
      {/* 使用通用的ProjectSidebar组件 */}
      <ProjectSidebar
        isOpen={isSidebarOpen}
        onClose={() => setIsSidebarOpen(false)}
        currentProjectName={projectName}
        showNewProjectButton={true}
        showBackToDashboard={true}
      />

      {/* 主内容区 */}
      <div className={`flex-1 transition-all duration-300 ease-in-out ${isSidebarOpen ? 'md:ml-64' : 'ml-0'}`}>
        <div className="bg-white shadow">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="flex justify-between items-center py-6">
              <div className="flex items-center flex-1">
                <button
                  onClick={() => setIsSidebarOpen(!isSidebarOpen)}
                  className="mr-4 text-gray-600 hover:text-gray-900"
                >
                  {isSidebarOpen ? <XMarkIcon className="h-6 w-6" /> : <Bars3Icon className="h-6 w-6" />}
                </button>
                <div className="flex-1">
                  <h1 className="text-3xl font-bold text-gray-900">{project?.name}</h1>
                  <p className="text-gray-600 mt-1">{project?.description}</p>
                  
                  {/* 团队成员显示 */}
                  {project && (
                    <div key={`project-members-${project.id}`} className="mt-3 flex items-center flex-wrap gap-2">
                      <span className="text-sm text-gray-500 mr-2">团队成员：</span>
                      {Array.isArray(projectMembers) && projectMembers.map((member) => (
                        <span
                          key={member.id}
                          className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-gray-100 text-gray-800"
                        >
                          <span 
                            key={`member-color-${member.id}`}
                            className="w-2 h-2 rounded-full mr-2" 
                            style={{ backgroundColor: member.color }}
                          ></span>
                          {member.name}
                          {currentUser && member.id !== currentUser.id && (
                            <button
                              onClick={() => removeMember(member.id)}
                              className="ml-2 text-gray-400 hover:text-red-600 focus:outline-none"
                            >
                              <XMarkIcon className="h-4 w-4" />
                            </button>
                          )}
                        </span>
                      ))}
                    </div>
                  )}
                </div>
              </div>
              <div className="flex items-center space-x-3">
                <button 
                  onClick={() => setIsCompactMode(!isCompactMode)}
                  className="font-bold py-2 px-4 rounded flex items-center transition-colors"
                  style={{ 
                    backgroundColor: isCompactMode 
                      ? (currentUser?.color || '#4F46E5')
                      : '#6B7280',
                    color: 'white'
                  }}
                  onMouseEnter={(e) => {
                    if (isCompactMode && currentUser?.color) {
                      e.currentTarget.style.backgroundColor = `${currentUser.color}CC`
                    } else if (!isCompactMode) {
                      e.currentTarget.style.backgroundColor = '#4B5563'
                    }
                  }}
                  onMouseLeave={(e) => {
                    if (isCompactMode) {
                      e.currentTarget.style.backgroundColor = currentUser?.color || '#4F46E5'
                    } else {
                      e.currentTarget.style.backgroundColor = '#6B7280'
                    }
                  }}
                  title={isCompactMode ? "显示所有已完成任务" : "隐藏已完成超过一周的任务"}
                >
                  <TrashIcon className="h-5 w-5 mr-2" />
                  {isCompactMode ? '显示全部' : '精简'}
                </button>
                <button 
                  onClick={() => setIsEditProjectModalOpen(true)}
                  className="text-white font-bold py-2 px-4 rounded flex items-center"
                  style={{ 
                    backgroundColor: currentUser?.color || '#4F46E5'
                  }}
                  onMouseEnter={(e) => {
                    if (currentUser?.color) {
                      e.currentTarget.style.backgroundColor = `${currentUser.color}CC`
                    }
                  }}
                  onMouseLeave={(e) => {
                    if (currentUser?.color) {
                      e.currentTarget.style.backgroundColor = currentUser.color
                    }
                  }}
                >
                  <PlusIcon className="h-5 w-5 mr-2" /> 项目管理
                </button>
              </div>
            </div>
          </div>
        </div>

        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
          <DragDropContext onDragEnd={handleDragEnd}>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
              {statusColumns.map((column) => (
                /*<div key={column.id} className={`${column.color} rounded-lg p-4 border border-gray-300 shadow-sm`}>*/
                <div key={column.id} className={`${column.color} rounded-lg p-4 border-2 border-gray-400 shadow-md hover:shadow-lg transition-shadow duration-200`}>
                  <div className="flex justify-between items-center mb-4">
                    <h3 className="font-semibold text-gray-800">{column.emoji} {column.title}</h3>
                    <button 
                      onClick={() => openNewTodoModal(column.id)}
                      className="p-1 rounded-full transition-colors"
                      style={{
                        color: currentUser?.color || '#4F46E5'
                      }}
                      onMouseEnter={(e) => {
                        if (currentUser?.color) {
                          e.currentTarget.style.backgroundColor = `${currentUser.color}20`
                        }
                      }}
                      onMouseLeave={(e) => {
                        e.currentTarget.style.backgroundColor = 'transparent'
                      }}
                      title={`添加新的 ${column.title} 任务`}
                    >
                      <PlusIcon className="h-5 w-5" />
                    </button>
                  </div>
                  
                  <Droppable droppableId={column.id}>
                    {(provided, snapshot) => (
                      <div
                        ref={provided.innerRef}
                        {...provided.droppableProps}
                        className={`min-h-[200px] transition-colors duration-200 ${
                          snapshot.isDraggingOver ? 'bg-opacity-50' : ''
                        }`}
                        style={{
                          backgroundColor: snapshot.isDraggingOver ? 'rgba(59, 130, 246, 0.1)' : 'transparent'
                        }}
                      >
                        <div className="space-y-2 max-h-[calc(100vh-300px)] overflow-y-auto">
                          {getFilteredTodos(column.id, todos[column.id] || []).map((todo, index) => (
                            <Draggable key={todo.id} draggableId={todo.id.toString()} index={index}>
                              {(provided, snapshot) => (
                                <div
                                  ref={provided.innerRef}
                                  {...provided.draggableProps}
                                  {...provided.dragHandleProps}
                                  className={`bg-white rounded-lg p-3 shadow-sm border border-gray-200 cursor-move transition-all duration-200 ${
                                    snapshot.isDragging ? 'shadow-lg transform rotate-2' : 'hover:shadow-md'
                                  }`}
                                >
                                  <div className="flex justify-between items-start mb-2">
                                    <div className="flex items-center space-x-2 flex-1">
                                      <div 
                                        className="w-3 h-3 rounded-full flex-shrink-0"
                                        style={{ backgroundColor: todo.creator_color }}
                                      ></div>
                                      <span className="text-xs text-gray-500 flex-shrink-0">
                                        {todo.creator_name}
                                      </span>
                                      {/* 用时标签 - 仅在已完成状态显示 */}
                                      {todo.status === '已完成' && todo.time_spent !== null && todo.time_spent !== undefined && (
                                        <span className="inline-block bg-green-100 text-green-800 text-xs px-2 py-1 rounded ml-2">
                                          用时: {todo.time_spent.toFixed(1)}天
                                        </span>
                                      )}
                                    </div>
                                    <button
                                      onClick={() => handleDeleteTodo(todo.id, todo.status)}
                                      className="text-gray-400 hover:text-red-500 transition-colors ml-2"
                                      title="删除任务"
                                    >
                                      <XMarkIcon className="h-4 w-4" />
                                    </button>
                                  </div>
                                  
                                  <div 
                                    className="text-sm text-gray-800 mb-2 cursor-pointer"
                                    onClick={() => openEditTodoModal(todo)}
                                  >
                                    {todo.content}
                                  </div>
                                  
                                  {todo.tags && (
                                    <div className="mb-2">
                                      {todo.tags.split(/[,\s]+/).map((tag, tagIndex) => (
                                        <span
                                          key={tagIndex}
                                          className="inline-block bg-blue-100 text-blue-800 text-xs px-2 py-1 rounded mr-1 mb-1"
                                        >
                                          {tag.trim()}
                                        </span>
                                      ))}
                                    </div>
                                  )}
                                  
                                  {todo.assignee_name && (
                                    <div className="flex items-center justify-between">
                                      <div className="flex items-center space-x-1">
                                        <span className="text-xs text-gray-500">分配给:</span>
                                        <div 
                                          className="w-2 h-2 rounded-full"
                                          style={{ backgroundColor: todo.assignee_color || '#888888' }}
                                        ></div>
                                        <span className="text-xs text-gray-700">{todo.assignee_name}</span>
                                      </div>
                                      <span className="text-xs text-gray-400">
                                        {new Date(todo.created_at).toLocaleDateString('zh-CN')}
                                      </span>
                                    </div>
                                  )}
                                  
                                  {!todo.assignee_name && (
                                    <div className="flex justify-end">
                                      <span className="text-xs text-gray-400">
                                        {new Date(todo.created_at).toLocaleDateString('zh-CN')}
                                      </span>
                                    </div>
                                  )}
                                </div>
                              )}
                            </Draggable>
                          ))}
                          {provided.placeholder}
                        </div>
                      </div>
                    )}
                  </Droppable>
                </div>
              ))}
            </div>
          </DragDropContext>
        </div>
      </div>

      {/* 新建项目模态框 */}
      <NewProjectModal
        isOpen={isNewProjectModalOpen}
        onClose={() => setIsNewProjectModalOpen(false)}
        onSuccess={() => {
          setIsNewProjectModalOpen(false)
        }}
      />

      {/* 编辑项目模态框 */}
      <NewProjectModal
        isOpen={isEditProjectModalOpen}
        onClose={() => setIsEditProjectModalOpen(false)}
        onSuccess={() => {
          setIsEditProjectModalOpen(false)
          fetchProjectAndTodos() // 刷新项目数据
        }}
        editMode={true}
        project={project}
        initialMembers={projectMembers}
      />

      {/* 新建/编辑任务模态框 */}
      <NewTodoModal
        isOpen={isNewTodoModalOpen}
        onClose={() => setIsNewTodoModalOpen(false)}
        onSuccess={handleTodoSubmitSuccess}
        currentStatus={currentTodoStatus || '待完成'}
        projectId={project?.id || 0}
        currentUserId={currentUser?.id || 0}
        projectMembers={projectMembers}
        editTodoData={editingTodo}
      />
    </div>
  )
} 